<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang>
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/hcigmoid/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic|Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/hcigmoid/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/hcigmoid/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/hcigmoid/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/hcigmoid/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/hcigmoid/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/hcigmoid/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="推荐,多样性,DPP,MAP,">





  <link rel="alternate" href="/hcigmoid/atom.xml" title="HCigmoid" type="application/atom+xml">






<meta name="description" content="论文引用: Chen, Laming, Guoxin Zhang, and Eric Zhou. “Fast greedy map inference for determinantal point process to improve recommendation diversity.” Advances in Neural Information Processing Systems. 201">
<meta name="keywords" content="推荐,多样性,DPP,MAP">
<meta property="og:type" content="article">
<meta property="og:title" content="Fast Greedy MAP for DPP 论文精读">
<meta property="og:url" content="http://guyuecanhui.gitee.io/hcigmoid/2020/07/29/paper-2018-hulu-dpp_map/index.html">
<meta property="og:site_name" content="HCigmoid">
<meta property="og:description" content="论文引用: Chen, Laming, Guoxin Zhang, and Eric Zhou. “Fast greedy map inference for determinantal point process to improve recommendation diversity.” Advances in Neural Information Processing Systems. 201">
<meta property="og:locale" content="default">
<meta property="og:updated_time" content="2020-07-29T15:02:20.306Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Fast Greedy MAP for DPP 论文精读">
<meta name="twitter:description" content="论文引用: Chen, Laming, Guoxin Zhang, and Eric Zhou. “Fast greedy map inference for determinantal point process to improve recommendation diversity.” Advances in Neural Information Processing Systems. 201">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/hcigmoid/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://guyuecanhui.gitee.io/hcigmoid/2020/07/29/paper-2018-hulu-dpp_map/">





  <title>Fast Greedy MAP for DPP 论文精读 | HCigmoid</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="default">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/hcigmoid/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">HCigmoid</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">Watch, learn and practise</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/hcigmoid/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/hcigmoid/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/hcigmoid/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/hcigmoid/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/hcigmoid/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://guyuecanhui.gitee.io/hcigmoid/hcigmoid/2020/07/29/paper-2018-hulu-dpp_map/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="古月残辉">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/hcigmoid/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="HCigmoid">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Fast Greedy MAP for DPP 论文精读</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-07-29T22:31:30+08:00">
                2020-07-29
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/hcigmoid/categories/论文精读/" itemprop="url" rel="index">
                    <span itemprop="name">论文精读</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/hcigmoid/2020/07/29/paper-2018-hulu-dpp_map/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/hcigmoid/2020/07/29/paper-2018-hulu-dpp_map/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i> 阅读数
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  3.9k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  16
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <div class="note success"><p><strong>论文引用:</strong> Chen, Laming, Guoxin Zhang, and Eric Zhou. “Fast greedy map inference for determinantal point process to improve recommendation diversity.” <em>Advances in Neural Information Processing Systems</em>. 2018. </p></div>
<p>内容推荐系统的设计宗旨是帮助用户从近乎无限的内容中找到自己喜欢的，为了这个目标，推荐系统最主要的两个任务就是探索与利用。利用的含义是当推荐系统有足够的依据推测用户当下可能喜欢什么的时候，将相关的内容推荐给用户；探索的含义是当推荐系统不知道用户是否喜欢某个品类的内容时，推荐少量这些品类的精选内容给用户，试探用户的反馈。利用的任务我们通常交给排序算法去解决；而探索的任务则困难得多，或者说风险高得多，它需要借助排序之外的手段去实现，例如基于用户实时反馈进行快速试探（冷启动），或者保持一定比例的流量专门做试探，等等。</p>
<p>无论使用哪种方式，这些试探的内容还是需要和排序的结果进行融合后，以一定的顺序展示给用户。由于这两类任务是不可比的，在进行融合时很容易就引入一些人工规则。人工规则设计的好其实也是一项技术活，更简单的办法是用算法来将这些结果进行融合，既能最大化用户的喜好，又能引入尽可能多样的内容。本文主要介绍基于 <strong>DPP</strong> 的多样性算法。</p>
<a id="more"></a>
<h3 id="DPP-简介"><a href="#DPP-简介" class="headerlink" title="DPP 简介"></a>DPP 简介</h3><p><strong>DPP</strong> 最早是在量子物理学中引入 $^{[1]}$，用于估计费米子系统在热平衡状态下的分布，它能够精确的描述粒子间的斥力。在内容推荐领域，我们可以把斥力与物品间的相似度进行类比：对于一个推荐列表，我们希望列表内的物品不是那么雷同，换句话说，我们希望相似的物品能够相互排斥，这就很符合 <strong>DPP</strong> 的建模场景，因此 <strong>DPP</strong> 经常被用于做物品的多样性调整。</p>
<p><strong>DPP</strong> 用于推荐系统中来提升推荐列表多样性时，最大的优势在于，它能够直接估计整个列表的得分，而不是两两之间进行比较，因此它对所有物品间的相似关系考虑的更加全面。它的精确定义可以参考 wiki $^{[2]}$。以内容推荐场景来说，给定一个离散的内容集合 <script type="math/tex">Z=\{1,2,\cdots,m\}</script> 及其关联的一个内核矩阵 $\boldsymbol{L}\in \mathbb{R}^{m\times m}$，一个 <strong>DPP</strong> $\mathcal{P}$ 是对该集合所有子集的一个概率度量，并且每个子集 $Y\subseteq Z$ 的概率与该子集投影在内核矩阵中的主子矩阵的行列式 $^{[3]} $ 成正比：</p>
<script type="math/tex; mode=display">
\mathcal{P}(Y)\propto \text{det}(\boldsymbol{L}_Y)</script><p>内核矩阵马上会介绍如何构造，这里只需要知道它是半正定的 (<strong>PSD</strong>, positive semidefinite)，因此 $\det(\boldsymbol{L}_Y) \ge 0$。举个例子，给定 $Z={1,2}$，<script type="math/tex">\boldsymbol{L}=\left[\begin{matrix}2,1\\1,1\end{matrix}\right]</script>，则 <strong>DPP</strong> $\mathcal{P}$ 对 $Z$ 所有子集的概率度量如下：</p>
<script type="math/tex; mode=display">
\begin{matrix}
\begin{align}
(未归一化)\\
\mathcal{P}(\varnothing)&\propto \text{det}(\varnothing)=1 \\
\mathcal{P}(\{1\})&\propto \text{det}([2])=2\\
\mathcal{P}(\{2\})&\propto \text{det}([1])=1\\
\mathcal{P}(\{1,2\})&\propto \text{det}(\boldsymbol{L})=1
\end{align}
\end{matrix}
\Rightarrow
\begin{matrix}
(归一化后)\\
\mathcal{P}(\varnothing)&=0.2\\
\mathcal{P}(\{1\})&=0.4\\
\mathcal{P}(\{2\})&=0.2\\
\mathcal{P}(\{1,2\})&=0.2
\end{matrix}</script><p>在这个例子里，我们想找到最大概率的集合就是 <script type="math/tex">\{1\}</script>，寻找这个集合的过程就是最大后验推断 (<strong>MAP</strong>, maximum a posteriori)。不幸的是，<strong>DPP</strong> 的 <strong>MAP</strong> 问题是 NP-hard 的；幸运的是，$\log(\det(\cdot))$ 是一个 submodular 函数 $^{[4]}$，而submodular 函数的贪心算法有 1/2 的最优近似保证。由此，文章基于 <strong>DPP</strong> 模型提出了一种 <strong>MAP</strong> 的贪心近似推断方法，将时间复杂度降到 $O(n^2m)$，其中，$m$ 表示候选集合内容数量，$n$ 表示待推荐的内容数量。本文只介绍单个短列表内的 <strong>DPP</strong> 模型推断，基于窗口的长列表的推断可以参考论文或者其他博客。</p>
<h3 id="DPP-建模"><a href="#DPP-建模" class="headerlink" title="DPP 建模"></a>DPP 建模</h3><p>前面简单介绍了 <strong>DPP</strong> 模型的概念和特点，接下来考虑将 <strong>DPP</strong> 模型应用到以下典型场景：从排序模型输出的列表 $Z$ 中选择 top $n$ 的内容 $Y$ 推荐给用户，既能保证列表里的内容都是用户感兴趣的，同时提升推荐列表的多样性。<strong>DPP</strong> 建模的核心在于内核矩阵的构建。</p>
<p>要保证用户感兴趣，也就是要保证推荐内容与用户的相关性，一般可以通过排序得分来度量，我们把列表 $Z$ 中内容的排序分记为 <script type="math/tex">\boldsymbol{r}=[r_1, r_2, \cdots, r_m]</script>。</p>
<p>而内容的多样性一般通过内容间是不是不相似来度量。相似度评估可以是隐式的，例如基于物品的 embedding；也可以是规则式的，比如只考察可读的几个维度：标签、分类、作者等，然后基于 <strong>Jaccard</strong> 相似度来计算。我们把列表 $Z$ 中内容两两间相似度记为 $\boldsymbol{S}$，其中，$\boldsymbol{S}_{i,j}$ 表示内容 $i,j$ 之间的相似度，相似度的取值需要缩放到区间 $[0,1]$。</p>
<p>那怎么生成内核矩阵呢？前面提到，内核矩阵需要是半正定的，因此可以被分解为 $\boldsymbol{L}=\boldsymbol{B}^\top \boldsymbol{B}$，其中，$\boldsymbol{B}\in\mathbb{R}^{m\times m}$ 的每一列 $\boldsymbol{b}_i$ 可以看成是相应内容的表示向量，这个表示向量既要考虑与用户的相关性，又能用于相似度计算，因此可以设计成 $\boldsymbol{b}_i=r_i \boldsymbol{f}_i$，$\boldsymbol{f}_i$ 表示内容 $i$ 的 embedding 向量，或者是元数据的 onehot 编码等。这样，</p>
<script type="math/tex; mode=display">
\boldsymbol{L}_{i,j}=\langle\boldsymbol{b}_i,\boldsymbol{b}_j\rangle=\langle r_i\boldsymbol{f}_i,r_j\boldsymbol{f}_j\rangle=r_ir_j\langle\boldsymbol{f}_i,\boldsymbol{f}_j\rangle=r_ir_j\boldsymbol{S}_{i,j}</script><p>写成矩阵的形式就是：</p>
<script type="math/tex; mode=display">
\boldsymbol{L}=\text{diag}(\boldsymbol{r}) \cdot \boldsymbol{S}\cdot \text{diag}(\boldsymbol{r})</script><p>为了能够贪心求解，我们对目标行列式取对数，得到 submodular 的目标，即找到最优的列表 $Y$ 来最大化：</p>
<script type="math/tex; mode=display">
\begin{align}
\log\mathcal{P}(Y) \propto \log\det(\boldsymbol{L}_{Y})&=\log\Big(\det\big(\text{diag}(\boldsymbol{r}_Y) \cdot \boldsymbol{S}_Y\cdot \text{diag}(\boldsymbol{r}_Y)\big)\Big) \\
&=\log\Big(\det\big(\text{diag}(\boldsymbol{r}_Y)\big) \cdot\det\big( \boldsymbol{S}_Y\big) \cdot\det\big(  \text{diag}(\boldsymbol{r}_Y)\big)\Big) \\
&=2\sum_{i\in Y}\log(r_i) + \log \det\big( \boldsymbol{S}_Y\big)
\end{align}</script><p>这里矩阵或者向量的下标为 $Y$ 表示得到 $Y$ 中所有元素在矩阵/向量的索引得到的主子矩阵/向量。这样，我们就能看出来，最终推荐列表 $Y$ 的 DPP 概率得分实际上是 $\sum_{i\in R}\log(r_i)$ 与 $\log \det\big( \boldsymbol{S}_Y\big)$ 的线性组合。前者表示内容 $i$ 的排序得分，后者表示 $Y$ 中内容的差异得分。</p>
<p>为了能够调整排序分与相似分的权重，可以将上式进一步调整成下式：</p>
<script type="math/tex; mode=display">
\begin{align}
\log\mathcal{P}(Y) &\propto \theta \cdot \sum_{i\in Y}r_i + (1-\theta)\cdot\log \det\big( \boldsymbol{S}_Y\big) \\
&\propto\frac{\theta}{2(1-\theta)} \cdot \sum_{i\in Y}r_i + \log \det\big( S_R\big)+ \frac{\theta}{2(1-\theta)} \cdot \sum_{i\in Y}r_i\\
&\overset{\alpha=\frac{\theta}{2(1-\theta)}}{=} \sum_{i\in Y}\log\big(e^{\alpha r_i}) + \log \det\big( \boldsymbol{S}_Y\big)+ \sum_{i\in Y}\log\big(e^{\alpha r_i})\\
&=\log\Big(\det\big(\text{diag}(e^{\alpha\boldsymbol{r}_Y}) \cdot \boldsymbol{S}_Y\cdot \text{diag}(e^{\alpha\boldsymbol{r}_Y})\big)\Big)
\end{align}</script><p>再回到内核矩阵上来，我们得到了一个新的 $\boldsymbol{L}_{Y} = \text{diag}(e^{\alpha\boldsymbol{r}_Y}) \cdot \boldsymbol{S}_Y\cdot \text{diag}(e^{\alpha\boldsymbol{r}_Y})$，其中，$\alpha=\frac{\theta}{2(1-\theta)}$，$\theta\in [0,1)$，$\theta$ 越大，排序得分的影响越大，$\theta$ 越小，列表中的内容差异越大。</p>
<p>需要说明的是，这种构造方法只有在 $\boldsymbol{S}$ 是半正定的情况下，才能保证 $\boldsymbol{L}$ 是半正定的。</p>
<h3 id="Fast-Greedy-MAP-Inference"><a href="#Fast-Greedy-MAP-Inference" class="headerlink" title="Fast Greedy MAP Inference"></a>Fast Greedy MAP Inference</h3><p>假设我们已经构造出内容推荐场景下的内核矩阵 $\boldsymbol{L}$，下面就需要贪心每次向最终推荐列表 $Y$ 中添加内容 $j$，使得我们的 submodular 的目标增益最大：</p>
<script type="math/tex; mode=display">
j = \arg \max_{i\in Z-Y} \log \det(\boldsymbol{L}_{Y\cup\{i\}}) - \log \det(\boldsymbol{L}_{Y})</script><p>首先，我们推导一下，要最大化目标增益，其实我们每次只需要找到一个内容 $i$，它在 $\boldsymbol{L} $ 主子矩阵 <script type="math/tex">\boldsymbol{L}_{Y\cup\{i\}}</script> 的 Cholesky 分解矩阵的对角元素最大即可。</p>
<p>具体来讲，如果 $\boldsymbol{L}$ 是半正定的，则 $\boldsymbol{L}$ 的任意主子矩阵 $\boldsymbol{L}_Y$ 也是半正定的，因此可以进行 Cholesky 分解。但是由于半正定矩阵的 Cholesky 分解不唯一，我们姑且假设 $\boldsymbol{L}_Y$ 是正定的（后面会讨论异常如何处理），则它可以被分解为：</p>
<script type="math/tex; mode=display">
\boldsymbol{L}_Y=\boldsymbol{V}\boldsymbol{V}^\top</script><p>这里 $\boldsymbol{V}$ 是一个下三角矩阵，并且对角线上的元素都是正实数；$Y$ 是我们目前根据贪心规则已经从候选列表 $Z$ 选出的部分的推荐结果。对于内容 $i\in Z-Y$，<script type="math/tex">Y'=Y\cup \{i\}</script> 在 $\boldsymbol{L} $ 上投影的主子矩阵 $\boldsymbol{L}_{Y’}$ 可以表示为：</p>
<script type="math/tex; mode=display">
\boldsymbol{L}_{Y'} = 
\left [\begin{matrix}
\boldsymbol{L}_{Y} & \boldsymbol{L}_{Y,i}\\
\boldsymbol{L}_{i,Y} & \boldsymbol{L}_{i,i}
\end{matrix}\right ]=
\left [\begin{matrix}
\boldsymbol{V} & \boldsymbol{0}\\
\boldsymbol{c}_i & d_i
\end{matrix}\right ]
\left [\begin{matrix}
\boldsymbol{V} & \boldsymbol{0}\\
\boldsymbol{c}_i & d_i
\end{matrix}\right ]^\top=
\left [\begin{matrix}
\boldsymbol{V}\boldsymbol{V}^\top & \boldsymbol{V}\boldsymbol{c}_i^\top\\
\boldsymbol{c}_i\boldsymbol{V}^\top+d_i\boldsymbol{c}_i^\top & \boldsymbol{c}_i\boldsymbol{c}_i^\top+d_i^2
\end{matrix}\right ] \qquad(1)</script><p>根据式 $(1)$ 可以得 <script type="math/tex">\det(\boldsymbol{L}_{Y'})</script> 与 <script type="math/tex">\det(\boldsymbol{L}_{Y})</script> 的关系：</p>
<script type="math/tex; mode=display">
\begin{align}\det(\boldsymbol{L}_{Y'}) = \det\left(\left [\begin{matrix}\boldsymbol{V} & \boldsymbol{0}\\\boldsymbol{c}_i & d_i\end{matrix}\right ]\left [\begin{matrix}\boldsymbol{V} & \boldsymbol{0}\\\boldsymbol{c}_i & d_i\end{matrix}\right ]^\top \right)&=\det\left(\left [\begin{matrix}\boldsymbol{V} & \boldsymbol{0}\\\boldsymbol{c}_i & d_i\end{matrix}\right ]\right)\det\left(\left [\begin{matrix}\boldsymbol{V} & \boldsymbol{0}\\\boldsymbol{c}_i & d_i\end{matrix}\right ]^\top\right) \\&=\left(\det(\boldsymbol{V})\cdot d_i\right)^2 \\&=\det(\boldsymbol{V}\boldsymbol{V}^\top)\cdot d_i^2\\&=\det(\boldsymbol{L}_Y)\cdot d_i^2\end{align}</script><p>因此，基于当前局部最优结果 $Y$，下一个被选中的内容 $j$ 满足：</p>
<script type="math/tex; mode=display">
j = \arg \max_{i\in Z-Y} \log \det(\boldsymbol{L}_{Y\cup\{i\}}) - \log \det(\boldsymbol{L}_{Y}) = \arg\max_{i\in Z-Y} \log(d_i^2)</script><p>也就是说，在给定当前推荐列表 $Y$ 的情况下，我们只需要计算所有剩下候选内容 $i\in Z-Y$ 对应的 $d_i$ 值即可，可以认为 $\log(d_i^2)$ 就是我们每次选中内容 $i$ 得到的边际增益，为了保证这个增益始终为正，需要保证 $d_i^2&gt;1$ (当然，这个增益物理含义不明确，实际上小于 $0$ 问题也不大)。</p>
<p>观察式 $(1)$ 可得：</p>
<script type="math/tex; mode=display">
d_i^2=\boldsymbol{L}_{i,i}-\parallel\boldsymbol{c}_i\parallel^2_2</script><p>正常来讲，我们需要从矩阵 $\boldsymbol{V}$ 的左上角开始，按行或者按列依次算出所有的 $\boldsymbol{V}_{k,l}$，最后才能得出 $d_i$ $^{[6]}$，但是这样的复杂度太高了。文章提出了一种迭代的计算方法，在每次得到最优推荐结果的同时，记录所有的 $\boldsymbol{c}_i$，并在计算下一轮最优结果时更新这些 $\boldsymbol{c}_i$。</p>
<p>怎么更新 $\boldsymbol{c}_i$ 呢？假设我们在某一轮已经找到最优的内容 $j$，在找的过程中，已经计算并保存所有的 $\boldsymbol{c}_k, \ k\in Z$；当我们再找下一个最优内容 $i$ 时，由于 $Y$ 中的内容数量会增加一个，$\boldsymbol{c}_i$ 的维度也会相应的增加一维，记待更新的向量为 $\boldsymbol{c}_i’=[\boldsymbol{c}_i, e_i]$。还是观察式 $(1)$ 的右上角项，易知在本轮：</p>
<script type="math/tex; mode=display">
\begin{align}
\left [\begin{matrix}
\boldsymbol{V} & \boldsymbol{0}\\
\boldsymbol{c}_j & d_j
\end{matrix}\right ]\boldsymbol{c}_i'^\top = \boldsymbol{L}_{Y',i}
=
\left [\begin{matrix}
\boldsymbol{L}_{Y,i}\\
\boldsymbol{L}_{j,i}
\end{matrix}\right ]
&\Rightarrow
\langle[\boldsymbol{c}_j d_j], \boldsymbol{c}_i'\rangle=\boldsymbol{L}_{j,i} \\
&\Rightarrow
\langle\boldsymbol{c}_j , \boldsymbol{c}_i\rangle+ d_j\cdot e_i=\boldsymbol{L}_{j,i}\\
&\Rightarrow 
e_i = \frac{\boldsymbol{L}_{j,i}-\langle\boldsymbol{c}_j , \boldsymbol{c}_i\rangle}{d_j}
\end{align}</script><p>由此可以进一步算出，</p>
<script type="math/tex; mode=display">
d_i'^2=\boldsymbol{L}_{i,i}-\parallel\boldsymbol{c}_i'\parallel^2_2=\boldsymbol{L}_{i,i}-\parallel\boldsymbol{c}_i\parallel^2_2 -e_i^2=d_i^2-e_i^2</script><p>初始时，$Y=\varnothing$，<script type="math/tex">d_i^2=\boldsymbol{L}_{i,i}</script>，<script type="math/tex">j=\arg \max_{i\in Z} d_i^2</script>。</p>
<h3 id="算法整体流程"><a href="#算法整体流程" class="headerlink" title="算法整体流程"></a>算法整体流程</h3><p>上面我们推导了内核矩阵如何构建，基于内核矩阵如何贪心的找到增益最高的推荐列表。最后总结一下整个算法流程（python 实现可参考 $[6]$）：</p>
<hr>
<h2 id="Fast-Greedy-MAP-Inference-for-DPP"><a href="#Fast-Greedy-MAP-Inference-for-DPP" class="headerlink" title="Fast Greedy MAP Inference for DPP"></a>Fast Greedy MAP Inference for DPP</h2><ol>
<li><strong>Input</strong>: candidates $Z=[0,1,\cdots m-1]$, similarity matrix of candidates $\boldsymbol{S}\in \mathbb{R}^{m\times m}$, ranking vector of candidates <script type="math/tex">\boldsymbol{r}=[r_0,r_1,\cdots,r_{m-1}]</script>, recommend item count $n$</li>
<li><strong>Initialize</strong>: $\boldsymbol{L} = \text{diag}(e^{\alpha\boldsymbol{r}}) \cdot \boldsymbol{S}\cdot \text{diag}(e^{\alpha\boldsymbol{r}})$, $\boldsymbol{C}=\boldsymbol{0}_{m\times n}$, $\boldsymbol{d}^2=\text{diag}(\boldsymbol{L})$, $j=\arg \max \boldsymbol{d}^2$, $Y=[j]$</li>
<li><strong>for</strong> $k$ <strong>in</strong> range($0$, $n-1$):</li>
<li>&emsp;&emsp;<script type="math/tex">\boldsymbol{e}=(\boldsymbol{L}_{j,:}-\boldsymbol{C}_{:,:k}\cdot \boldsymbol{C}_{j,:k})/ \sqrt{\boldsymbol{d}^2_j}</script></li>
<li>&emsp;&emsp;$\boldsymbol{C}_{:,k} = \boldsymbol{e}$</li>
<li>&emsp;&emsp;$\boldsymbol{d}^2_j = -\infty$</li>
<li>&emsp;&emsp;$j=\arg \max \boldsymbol{d}^2$</li>
<li>&emsp;&emsp;<strong>if</strong> $\boldsymbol{d}^2_j&lt;\epsilon$:</li>
<li>&emsp;&emsp;&emsp;&emsp;<strong>break</strong></li>
<li>&emsp;&emsp;$Y=[Y, j]$</li>
<li><strong>return</strong> $Y$</li>
</ol>
<hr>
<p>前面提到，我们假设 $\boldsymbol{S}$ 和 $\boldsymbol{L} $ 是半正定的，但是在推导迭代公式的时候却假设 $\boldsymbol{L}_Y $ 是正定的，因此在实际计算的时候可能得到 $d_j=0$，导致第 4 步的数值不稳定，因此在第 8 步引入一个很小的 $\epsilon&gt;0$，当 $d_j^2&lt;\epsilon$ 时，就进入异常处理程序。这里写的是直接返回结果，实际也可以将列表用某种策略填充到 $n$ 个再返回。</p>
<p>什么情况下会发生这个问题呢？回顾前文，如果有两个内容 $i,j$ 的表征向量线性相关/元数据完全相同，这个时候 $\boldsymbol{b}_i,\boldsymbol{b}_j$ 是线性相关的，如果它们都被选到推荐列表 $Y$ 中时，就会导致 $\det(\boldsymbol{L}_Y )=0$，说明此时 $\boldsymbol{L}_Y $ 半正定，其 Cholesky 分解的矩阵 $\boldsymbol{V}$ 对角线元素为 $0$，即 $d_j=0$。</p>
<p>这种情况在现实中是可能出现的，可以考虑在计算相似矩阵 $\boldsymbol{S}$ 的时候，为每两个内容的相似度加上一个小的随机数（要对称的加），保证 $\boldsymbol{S}$ 是正定的即可，但是这种方式可能对推荐结果有一定的影响。当然，如果 $Z$ 足够多，而且里面内容足够多样，这种情况出现的概率就非常低了。</p>
<h3 id="参考文献"><a href="#参考文献" class="headerlink" title="参考文献"></a>参考文献</h3><p>[1] Macchi, Odile. “The coincidence approach to stochastic point processes.” <em>Advances in Applied Probability</em> 7.1 (1975): 83-122.</p>
<p>[2] Determinantal point process. <a href="https://en.wikipedia.org/wiki/Determinantal_point_process" target="_blank" rel="noopener">https://en.wikipedia.org/wiki/Determinantal_point_process</a></p>
<p>[3] 正定矩阵. <a href="https://zh.wikipedia.org/wiki/%E6%AD%A3%E5%AE%9A%E7%9F%A9%E9%98%B5" target="_blank" rel="noopener">https://zh.wikipedia.org/wiki/%E6%AD%A3%E5%AE%9A%E7%9F%A9%E9%98%B5</a></p>
<p>[4] Submodular函数. <a href="https://guyuecanhui.gitee.io/hcigmoid/2018/08/16/sub-modular/">https://guyuecanhui.gitee.io/hcigmoid/2018/08/16/sub-modular/</a></p>
<p>[5] Cholesky分解. <a href="https://zh.wikipedia.org/wiki/Cholesky%E5%88%86%E8%A7%A3" target="_blank" rel="noopener">https://zh.wikipedia.org/wiki/Cholesky%E5%88%86%E8%A7%A3</a></p>
<p>[6] fast-map-dpp. laming-chen. <a href="https://github.com/laming-chen/fast-map-dpp/blob/master/dpp.py" target="_blank" rel="noopener">https://github.com/laming-chen/fast-map-dpp/blob/master/dpp.py</a></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/hcigmoid/tags/推荐/" rel="tag"># 推荐</a>
          
            <a href="/hcigmoid/tags/多样性/" rel="tag"># 多样性</a>
          
            <a href="/hcigmoid/tags/DPP/" rel="tag"># DPP</a>
          
            <a href="/hcigmoid/tags/MAP/" rel="tag"># MAP</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/hcigmoid/2020/07/04/paper-2020-noha-magnn/" rel="next" title="MA-GNN 论文精读">
                <i class="fa fa-chevron-left"></i> MA-GNN 论文精读
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/hcigmoid/2020/12/05/weighted-sample/" rel="prev" title="加权随机采样">
                加权随机采样 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">古月残辉</p>
              <p class="site-description motion-element" itemprop="description">总结心得</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/hcigmoid/archives/">
              
                  <span class="site-state-item-count">32</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/hcigmoid/categories/index.html">
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/hcigmoid/tags/index.html">
                  <span class="site-state-item-count">78</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/hcigmoid/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="mailto:guyuecanhui@icloud.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#DPP-简介"><span class="nav-number">1.</span> <span class="nav-text">DPP 简介</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#DPP-建模"><span class="nav-number">2.</span> <span class="nav-text">DPP 建模</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Fast-Greedy-MAP-Inference"><span class="nav-number">3.</span> <span class="nav-text">Fast Greedy MAP Inference</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#算法整体流程"><span class="nav-number">4.</span> <span class="nav-text">算法整体流程</span></a></li></ol><li class="nav-item nav-level-2"><a class="nav-link" href="#Fast-Greedy-MAP-Inference-for-DPP"><span class="nav-number"></span> <span class="nav-text">Fast Greedy MAP Inference for DPP</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#参考文献"><span class="nav-number">1.</span> <span class="nav-text">参考文献</span></a></li></ol></li></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2018 &mdash; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">古月残辉</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">58.2k</span>
  
</div>









<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i> 访问人数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i> 总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/hcigmoid/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/hcigmoid/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/hcigmoid/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/hcigmoid/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/hcigmoid/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/hcigmoid/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/hcigmoid/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/hcigmoid/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/hcigmoid/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/hcigmoid/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/hcigmoid/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/hcigmoid/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/hcigmoid/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: '6du4Ppc2TvUuhcccRHSDNH2v-gzGzoHsz',
        appKey: 'zOKNml4W1Bq3OTzEuLt5hUjI',
        placeholder: '感谢阅读！欢迎评论！',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/hcigmoid/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  

</body>
</html>
